package com.demo.cms.security.access;

import java.util.Date;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;

import com.demo.common.NetUtils;
import com.demo.common.StringUtils;
import com.demo.core.model.Member;
import com.demo.core.model.Site;
import com.demo.core.model.User;
import com.demo.core.service.base.MemberService;
import com.demo.core.service.base.SiteService;
import com.demo.security.access.impl.RoleAuthenticationSuccessHandler;
import com.demo.security.access.model.PlatformUser;
import com.demo.security.access.model.SecurityUser;
import com.demo.security.impl.UserDetailsWrapper;

/**
 * CMS系统用户登录后根据其所具有的角色来进行页面跳转
 * 继承{@link com.demo.security.access.impl.RoleAuthenticationSuccessHandler}
 * 实现用户登录的记录和动态替换domain地址
 * @author ryuu.kk
 */
public class CmsRoleAuthenticationSuccessHandler extends RoleAuthenticationSuccessHandler {

	/**
	 * 站点访问的Service
	 */
	private SiteService siteService;
	
	/**
	 * Member服务
	 */
	private MemberService memberService;
	
	@Override
	public String getBackUrl(HttpServletRequest httpservletrequest,	HttpServletResponse httpservletresponse) {
		String backUrl = "";
		backUrl = (String) httpservletrequest.getAttribute(REDIRECT_URL);
		if (!StringUtils.hasText(backUrl)) {
			backUrl = httpservletrequest.getParameter(REDIRECT_URL);
		}
		return backUrl;
	}

	@Override
	public String createTargetUrl(String url) {
		String marker = "%{siteUri}";
		if (url.indexOf(marker) < 0) {
			return url;
		}
		Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
		Object objPrincipal = authentication.getPrincipal();
		if (objPrincipal instanceof UserDetailsWrapper) {
			UserDetailsWrapper<SecurityUser, Object> userDetails = (UserDetailsWrapper<SecurityUser, Object>)objPrincipal;
			if (userDetails.getCurrentUser() != null) {
				Site site = siteService.findByDomain("cms");
				return url.replace(marker, site.getBaseDomain());
			}
		}
		return null;
	}
	
	@Override
	public void preLoginChecker(SecurityUser user,
			HttpServletRequest httpservletrequest,
			HttpServletResponse httpservletresponse,
			Authentication authentication) throws ServletException {
		Site site = (Site) httpservletrequest.getSession().getAttribute("MultisiteSiteContext");
		Long userId = user.getId();
		Long siteId = site.getId();
		
		// 内置账户不进行处理
		if (user.getUserName().equals("root" )) {
			return;
		}
			
		Member member = null;
		// 获得认证委托信息
		Object principal = authentication.getPrincipal();
		// 获得会员信息
		if (principal instanceof PlatformUser) {
			Object obj = ((PlatformUser<?>)principal).getModel();
			if (obj instanceof Member) {
				member = (Member)obj;
			} else {
				member = memberService.find(userId, siteId);
			}
		}
		
		if (member == null) {
			throw new ServletException(" Not found this member in [Site:" + siteId + " & User:" + userId + "]"); 
		}
		String currentIP = NetUtils.getIpAddr(httpservletrequest);

		// 更新上次登录时间
		memberService.updateLastLogin(member.getId(), member.getCurrentLoginTime(), member.getCurrentLoginIp());
		// 更新本次登录时间
		memberService.updateCurrentLogin(member.getId(), new Date(), currentIP, member.getLoginCount() + 1);
	}

	public void setSiteService(SiteService siteService) {
		this.siteService = siteService;
	}

	public void setMemberService(MemberService memberService) {
		this.memberService = memberService;
	}
}
